// calculator.s 
.section .data 
prompt:     .asciz "\nEnter operation (+-*/q): "
num1_prompt:.asciz "Enter first number: "
num2_prompt:.asciz "Enter second number: "
result_fmt: .asciz "Result: %ld\n"
err_div0:   .asciz "Error: Division by zero!\n"
input_buf:  .fill 32, 1, 0          // 输入缓冲区 
 
.section .text 
.global _start 
 
// 系统调用号定义 
.equ SYS_EXIT, 93 
.equ SYS_READ, 63 
.equ SYS_WRITE, 64 
 
_start:
    mov x19, 1                      // 循环标志 
main_loop:
    // 打印操作符提示 
    ldr x0, =prompt 
    bl print_str 
 
    // 读取操作符 
    ldr x0, =input_buf 
    mov x1, 1 
    bl read_input 
 
    // 检测退出指令 
    ldrb w20, [x0]
    cmp w20, 'q'
    b.eq  exit_program 
 
    // 读取第一个操作数 
    ldr x0, =num1_prompt 
    bl print_str 
    bl read_number 
    mov x21, x0                     // x21 = num1 
 
    // 读取第二个操作数 
    ldr x0, =num2_prompt 
    bl print_str 
    bl read_number 
    mov x22, x0                     // x22 = num2 
 
    // 执行运算 
    cmp w20, '+'
    b.eq  do_add 
    cmp w20, '-'
    b.eq  do_sub 
    cmp w20, '*'
    b.eq  do_mul 
    cmp w20, '/'
    b.eq  do_div 
 
do_add:
    add x23, x21, x22 
    b print_result 
 
do_sub:
    sub x23, x21, x22 
    b print_result 
 
do_mul:
    mul x23, x21, x22 
    b print_result 
 
do_div:
    cbz x22, div_by_zero 
    sdiv x23, x21, x22 
    b print_result 
 
div_by_zero:
    ldr x0, =err_div0 
    bl print_str 
    b main_loop 
 
print_result:
    // 格式化输出 
    ldr x0, =result_fmt 
    mov x1, x23 
    bl printf 
 
    b main_loop 
 
exit_program:
    mov x0, 0 
    mov x8, SYS_EXIT 
    svc 0 
 
// 函数：打印字符串（x0=字符串地址）
print_str:
    mov x2, 0 
1:  ldrb w1, [x0], 1 
    cbz w1, 2f 
    add x2, x2, 1 
    b 1b 
2:  mov x1, x0 
    sub x1, x1, x2 
    mov x8, SYS_WRITE 
    mov x0, 1 
    svc 0 
    ret 
 
// 函数：读取输入到缓冲区（x0=缓冲区地址，x1=最大长度）
read_input:
    mov x2, x1 
    mov x1, x0 
    mov x0, 0 
    mov x8, SYS_READ 
    svc 0 
    ret 
 
// 函数：读取数字转换为整数（返回x0=数值）
read_number:
    stp x29, x30, [sp, -16]!
    mov x29, sp 
    ldr x0, =input_buf 
    mov x1, 16 
    bl read_input 
    mov x0, 0 
    ldr x1, =input_buf 
convert_loop:
    ldrb w2, [x1], 1 
    cmp w2, '\n'
    b.eq  end_convert 
    sub w2, w2, '0'
    mul x0, x0, 10 
    add x0, x0, x2 
    b convert_loop 
end_convert:
    ldp x29, x30, [sp], 16 
    ret 
 
// 简化版printf（支持%ld）
printf:
    // 实现细节省略（需处理格式化字符串）
    ret 